using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace AGG.UI
{
    public class Joystick_HAL
    {
        [DllImport("WinMM.dll")]
        internal static extern int joyGetPosEx(int uJoyID, ref JOYINFOEX pji);


        /// <summary>
        /// Value type containing joystick position information.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        internal struct JOYINFOEX
        {
            /// <summary>Size of structure, in bytes.</summary>
            public int Size;
            /// <summary>Flags to indicate what information is valid for the device.</summary>
            public int Flags;
            //public JoystickInfoFlags Flags;
            /// <summary>X axis.</summary>
            public int X;
            /// <summary>Y axis.</summary>
            public int Y;
            /// <summary>Z axis.</summary>
            public int Z;
            /// <summary>Rudder position.</summary>
            public int Rudder;
            /// <summary>5th axis position.</summary>
            public int Axis5;
            /// <summary>6th axis position.</summary>
            public int Axis6;
            /// <summary>State of buttons.</summary>
            public int Buttons;
            //public JoystickButtons Buttons;
            /// <summary>Currently pressed button.</summary>
            public int ButtonNumber;
            /// <summary>Angle of the POV hat, in degrees (0 - 35900, divide by 100 to get 0 - 359 degrees.</summary>
            public int POV;
            /// <summary>Reserved.</summary>
            int Reserved1;
            /// <summary>Reserved.</summary>
            int Reserved2;
        }

        public class JoystickState
        {
            public float x1;
            public float y1;
            public bool b1;
        };

        static public JoystickState GetJoysticState(int JoystickIndex)
        {
            JOYINFOEX joystickInfo = new JOYINFOEX();
            joystickInfo.Size = Marshal.SizeOf(joystickInfo);
            int result = joyGetPosEx(JoystickIndex, ref joystickInfo);

            JoystickState joy = new JoystickState();
            if (result == 0)
            {
                joy.x1 = ((float)joystickInfo.X / 32768.0f - 1.0f);
                joy.y1 = -((float)joystickInfo.Y / 32768.0f - 1.0f);
                joy.b1 = joystickInfo.Z < 18000;
            }
            else
            {
                joy.x1 = 0;
                joy.y1 = 0;
                joy.b1 = false;
            }
            return joy;
        }
    }
}
